package com.yf.controller.api;

import com.yf.annotation.IgnoreAuth;
import com.yf.annotation.LoginUser;
import com.yf.entity.TokenEntity;
import com.yf.entity.UserEntity;
import com.yf.entity.WxUser;
import com.yf.response.R;
import com.yf.service.TokenService;
import com.yf.service.UserService;
import com.yf.service.WxAppService;
import com.yf.service.WxWebService;
import com.yf.service.im.GroupUserService;
import com.yf.service.meetingUser.MeetingUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;


@RestController
@RequestMapping("/api")
public class ApiLoginController {



    @PostMapping("/register")
    @IgnoreAuth
    public R register(String phone,String password,String name,String uuid,String captcha,@RequestParam(required = false) String parentPhone){
        TokenEntity tokenEntity =  userService.registerUser(phone,password,name,uuid,captcha,parentPhone);
        return R.ok("登录成功",tokenEntity).putExtra("userName",name);
    }


    /**
     * 微信公众号获取code
     *
     * @return
     */
    @GetMapping("/wx/code")
    @IgnoreAuth
    public void wxCode(String backUrl, HttpServletResponse response) throws IOException {
        String codeUrl = wxWebService.getCodeUrl(backUrl);
        //带上code之后会跳转回去
        response.sendRedirect(codeUrl);
    }

    /**
     * 微信公众号登录
     *
     * @param code
     * @param parentId
     * @return
     */
    @PostMapping("/wx/web/login")
    @IgnoreAuth
    public R wxWebLogin(String code, @RequestParam(required = false) Long parentId, String meeting) {
        TokenEntity token;
        WxUser wxUser = wxWebService.getWxUser(code);
        UserEntity userEntity = userService.findByUnionId(wxUser.getUnionId());
        if (userEntity == null) {
            token = userService.registerUser(wxUser, parentId);
        } else {
            //更新用户
            userEntity.setOpenId(wxUser.getOpenId());
            userEntity.setPayId(wxUser.getOpenId());
            userEntity.setAvatar(wxUser.getHeadImgUrl());
            userService.update(userEntity);
            token = userService.validateLogin(userEntity);
        }

        //找出用户的所有群ID
        List<Long> groupIds = groupUserService.findGroupIdByUserId(userEntity.getId());

        //年会抽奖用户
        if ("1".equals(meeting)) {
            meetingUserService.registerUser(wxUser);
        }

        return R.ok("登录成功", token).putExtra("wxUser", wxUser).putExtra("groupIds", groupIds);
    }


    /**
     * 小程序登录 关注过才能返回UnionId
     *
     * @param code
     * @param parentId
     * @return
     */
    @PostMapping("/wx/login")
    @IgnoreAuth
    public R wxLogin(String encryptedData, String code, String iv, @RequestParam(required = false) Long parentId) {
        TokenEntity token;
        //先获取key
        WxUser wxUser = wxAppService.getOpenIdAndSessionKey(code);
        wxUser = wxAppService.getWxUser(encryptedData, wxUser.getSessionKey(), iv);
        UserEntity userEntity = userService.findByUnionId(wxUser.getUnionId());
        if (userEntity == null) {
            token = userService.registerUser(wxUser, parentId);
        } else {
            token = userService.validateLogin(userEntity);
        }
        return R.ok("登录成功", token);
    }

    /**
     * 获取token
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping("/wx/testLogin")
    @IgnoreAuth
    public R testLogin(Long userId) {
        TokenEntity token = tokenService.createToken(userId);
        WxUser wxUser = new WxUser();
        UserEntity userEntity = userService.get(token.getUserId());
        wxUser.setHeadImgUrl(userEntity.getAvatar());
        wxUser.setNickName(userEntity.getName());
        return R.ok("登录成功", token).putExtra("wxUser", wxUser);
    }




    /**
     * 手机号+验证码登录
     * @param account
     * @param password
     * @param uuid
     * @param kaptcha
     * @return
     */
    @GetMapping("/captcha/login")
    @IgnoreAuth
    public R loginByKaptcha(String account, String password, String uuid, String captcha) {
        UserEntity userEntity = userService.loginByPassword(account, password, uuid, captcha);
        TokenEntity token = tokenService.createToken(userEntity.getId());
        return R.ok("登录成功", token);
    }

    /**
     * 账号密码登录
     *
     * @param account
     * @param password
     * @param uuid
     * @param captcha
     * @return
     */
    @PostMapping("/password/login")
    @IgnoreAuth
    public R loginByPassword(String account, String password, String uuid, String captcha) {
        UserEntity userEntity = userService.loginByPassword(account, password, uuid, captcha);
        TokenEntity token = tokenService.createToken(userEntity.getId());
        return R.ok("登录成功", token).putExtra("userName",userEntity.getName());
    }

    /**
     * 获取验证码
     *
     * @param uuid
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/captcha")
    @IgnoreAuth
    public void captcha(String uuid, HttpServletResponse response) throws IOException {
        BufferedImage image = userService.createImageCaptcha(uuid);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }


    @Autowired
    private UserService userService;


    @Autowired
    private WxAppService wxAppService;

    @Autowired
    private WxWebService wxWebService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private MeetingUserService meetingUserService;

    @Autowired
    private GroupUserService groupUserService;

}
